<template>
  <div class="header w">
    <!-- 搜索区域 -->
    <input v-model="keyword" class="search_input" type="text" placeholder="请输入关键词" />
    <div class="search_content" v-show="keyword">
      <ul>
        <li class="search_item border_bottom" v-for="item of list" :key="item.goods_id" @click="getGoodDetail(item.goods_id)">{{ item.goods_name }}</li>
        <li class="search_item border_bottom" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'Search',
  data () {
    return {
      // 搜索关键字
      keyword: '',
      // 搜索结果
      list: [],
      timer: null
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        this.goodsList.forEach(item => {
          if (item.goods_name.indexOf(this.keyword) > -1) {
            result.push(item)
          }
        })
        this.list = result
      }, 100)
    }
  },
  computed: {
    ...mapState(['goodsList']),
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    // 跳转到商品详情页
    getGoodDetail (id) {
      this.$store.commit('getGoodDetail', id)
      this.$router.push('/detail')
    }
  }
}
</script>

<style lang="less" scoped>
.header {
  position: relative;
  padding-top: .2rem;
}
// 搜索框
.search_input {
  // box-sizing: border-box;
  width: 100%;
  height: 1rem;
  line-height: 1rem;
  font-size: .48rem;
  color: #999;
  text-align: center;
  border-radius: .5rem;
  background-color: #fff;
  padding: 0 .2rem;
}
// 搜索结果列表
.search_content {
  z-index: 99;
  position: absolute;
  top: 1.2rem;
  left: .4rem;
  right: .4rem;
  background: #eee;
  .search_item {
    line-height: 1rem;
    font-size: .48rem;
    padding-left: .2rem;
    background: #fff;
    color: #666;
  }
  .border_bottom {
    border-bottom: .02rem solid #eee;
  }
}
</style>
